package com.ux.effect
{
	import com.greensock.TweenMax;
	import com.greensock.data.TweenMaxVars;
	import com.greensock.easing.Cubic;
	
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.filters.BlurFilter;
	import flash.utils.Timer;
	
	
	/**
	 * @author winnie
	 */	
	public class Rain extends Sprite
	{
		
		private var wid : Number;
		private var hei : Number;
		private var timer : Timer;
		private var amount:Number;
		private var rainMakeInterval:Number;
		
		public function Rain( _wid : Number=600, _hei : Number = 600, _amount:Number = 20, _rainMakeInterval:Number = 0.05 )
		{
			super();
			
			wid = _wid;
			hei = _hei;
			amount = _amount;
			rainMakeInterval = _rainMakeInterval;
			
			timer = new Timer( rainMakeInterval*1000, 1 );
			timer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete );
		}
			
		
		private function onTimerComplete( e:TimerEvent ):void 
		{
			timer.start();
			makeRain();
		}
		
		private function makeRain():void
		{
			var len:int = amount;
			for (var i:int = 0; i < len; i++) 
			{
				var rain : Shape = createRain();
				var tween : TweenMaxVars = new TweenMaxVars();
				tween.onComplete( rainDropComplete , [ rain ] );
//				tween.y = hei+50;
				tween.ease( Cubic.easeIn );
				
				tween.bezierThrough( [ {x:rain.x-(rain.rotationZ*10), y:hei+50} ] );
				
				TweenMax.to( rain, 2, tween );
			}
		}
		
		private function rainDropComplete( rain:Shape ):void
		{
			removeChild( rain );
		}
		
		private function createRain():Shape
		{
			var rain : Shape = new Shape();
			rain.graphics.lineStyle( 1,0xffffff );
			rain.graphics.lineTo( 0, 22 );
			rain.graphics.moveTo( 0, rain.height+1 );
			rain.graphics.lineTo( 0, rain.height+1+4 );
			rain.graphics.moveTo( 0, rain.height+1 );
			rain.graphics.lineTo( 0, rain.height+1+6 );
			rain.graphics.moveTo( 0, rain.height+1 );
			rain.graphics.lineTo( 0, rain.height+1+12 );
			
			addChild( rain );
			
			rain.alpha = 0.8;
			rain.x = Math.min( Math.random() * wid , wid )+100;
			rain.y = Math.random() * hei - hei-100;
			
			var blur : BlurFilter = new BlurFilter();
			rain.filters = [ blur ];
			var rotaion : Number = Math.min( 4, (wid / rain.x) ) * 10;

			rain.rotationZ = rotaion;
			
			return rain;
		}
		
		
		
		
		//-----------------------------------------------------------------------------------
		//
		// api
		//
		//-----------------------------------------------------------------------------------
		
		public function play():void 
		{
			timer.start();
		}
		
		public function stop(_disappearDuration:Number=2):void 
		{
			timer.stop();
			
			var len:int = numChildren;
			for (var i:int = 0; i < len; i++) 
			{
				var rain : Shape = getChildAt( i ) as Shape;
				TweenMax.to( rain, _disappearDuration, {alpha:0, delay:1} );
			}
		}
	}
}










